package user

import (
	"gpt-api/framework/ginplus"
	"gpt-api/framework/log"
	"gpt-api/pkg/model"
	"time"

	"github.com/gin-gonic/gin"
)

// AddEvent 增加事件信息
func (h *Handler) AddEvent(c *gin.Context) error {
	var req struct {
		Title string `json:"title" binding:"required"`
	}

	if err := c.Bind(&req); err != nil {
		return ginplus.ReplyBadRequest(c, err)
	}

	info := model.Events{
		Title: req.Title,
	}

	log.Info("Adding event", log.Var("event", info))
	err := h.db.Create(&info).Error
	if err != nil {
		return ginplus.ReplyInternalError(c, err)
	}

	return ginplus.ReplyJSON(c, info)
}

// UpdateEvent 更新事件信息
func (h *Handler) UpdateEvent(c *gin.Context) error {
	var req struct {
		Title    string    `json:"title"`
		Type     string    `json:"type"`
		Time     time.Time `json:"time"`
		Location string    `json:"location"`
		Details  string    `json:"details"`
		ImageURL string    `json:"image_url"`
	}

	id := c.Param("id") // 从URL中获取事件ID
	if err := c.Bind(&req); err != nil {
		return ginplus.ReplyBadRequest(c, err)
	}

	var info model.Events
	if result := h.db.First(&info, id).Error; result != nil {
		return ginplus.ReplyNotFound(c, result)
	}

	// 更新事件字段
	info.Title = req.Title

	info.UpdatedAt = time.Now()

	log.Info("Updating event", log.Var("event", info))
	err := h.db.Save(&info).Error
	if err != nil {
		return ginplus.ReplyInternalError(c, err)
	}

	return ginplus.ReplyJSON(c, info)
}

// GetEvents 获取事件列表
func (h *Handler) GetEvents(c *gin.Context) error {
	var events []model.Events
	if err := h.db.Find(&events).Error; err != nil {
		return ginplus.ReplyInternalError(c, err)
	}

	log.Info("Getting events", log.Var("events", events))
	return ginplus.ReplyJSON(c, events)
}
